<template>
  <section class="todoapp">
    <!-- 头部 -->
    <todo-header @add="handleAdd"></todo-header>

    <!-- This section should be hidden by default and shown when there are todos -->

    <!-- 主体 -->
    <todo-main :list="listTwo" @del="handleDel" @state="handleState" @changeAll="handleAll"></todo-main>

    <!-- This footer should be hidden by default and shown when there are todos -->

    <!-- 底部 -->
    <todo-footer :list="list" @delCompleted="handleClear" 
    :flag="flag"
    @changeFlag="val => {flag = val}"></todo-footer>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      list: JSON.parse(localStorage.getItem('todo')) || [],
      flag: 'a'
    };
  },
  methods: {
    handleDel(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    handleAdd (todoText) {
      this.list.unshift({ 
        id: Date.now(), 
        name: todoText, 
        isDone: false 
      })
    },
    handleState (id) {
      // console.log(id)
      const res = this.list.find(item => item.id == id)
      res.isDone = !res.isDone
    },
    handleClear () {
      this.list = this.list.filter(item => item.isDone !== true)
    },
    handleAll (val) {
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed: {
    listTwo () {
        if (this.flag === 'a') {
          return this.list
        } else if (this.flag === 'b') {
          return this.list.filter(item => item.isDone === false)
        } else {
          return this.list.filter(item => item.isDone === true)
        }
    }
  },
  watch: {
    list: {
      handler (val) {
        localStorage.setItem('todo', JSON.stringify(val))
      },
      deep: true
    }
  }
}
</script>

<style></style>
